package com.gexiao.servlet;

import cn.hutool.core.lang.Console;

import javax.servlet.AsyncContext;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value = "/async", asyncSupported = true)
public class HelloAsyncServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        Console.log("{},耗时：{}", Thread.currentThread(), System.currentTimeMillis());
        //1.支持异步处理asyncSupported = true
        //2.开启异步模式
        AsyncContext asyncContext = req.startAsync();
        asyncContext.start(() -> {
            try {
                doSomeThing();
                asyncContext.complete();
                ServletResponse response = asyncContext.getResponse();
                response.getWriter().write("hello async...");
            } catch (InterruptedException | IOException e) {
                e.printStackTrace();
            }
        });
        Console.log("{},耗时：{}", Thread.currentThread(), System.currentTimeMillis());
    }

    private void doSomeThing() throws InterruptedException {
        Thread.sleep(3000);
        Console.log("{},耗时：{}", Thread.currentThread(), System.currentTimeMillis());
    }
}
